/**
 * module:  疫苗记录
 * avator:   渣
 * table:  nc_vaccine_log,nc_livestock,nc_pasture,nc_house
 */
var express = require('express');
var router = express.Router();
var zSend = require('./controller');

const db = require('../../../db/db');


function queryAsync(sql) {
  return new Promise((resolve, reject) => {
    db.query(sql, (err, results) => {
      if (err) reject(err);
      else resolve(results);
    });
  });
}

router.get('/list', async (req, res, next) => {
  try {
    const { currentPage = 1, pageSize = 5, searchValue = '', F_Org_Id = '', F_HouseId = '' } = req.query;

    // 参数验证
    if (isNaN(currentPage) || isNaN(pageSize)) {
      return res.send(zSend('参数错误', 400));
    }

    const parsedPage = parseInt(currentPage);
    const parsedSize = parseInt(pageSize);
    
    if (parsedPage <= 0 || parsedSize <= 0) {
      return res.send(zSend('参数错误', 400));
    }

    // 构建基础查询条件（不含LIMIT/OFFSET）
    let baseQuery = `
      SELECT l.F_Title, l.F_IMEI, v.*, p.F_Title as F_PastureTitle, h.F_Title as F_HouseTitle
      FROM nc_livestock as l 
      left JOIN nc_vaccine_log as v ON v.F_liveid = l.F_Id
      left JOIN nc_pasture as p ON p.F_Id = l.F_Org_Id
      left JOIN nc_house as h ON h.F_Id = l.F_HouseId
      WHERE 1=1
      ${searchValue ? `AND (l.F_Title LIKE '%${searchValue}%' OR l.F_IMEI LIKE '%${searchValue}%')` : ''}
      ${F_Org_Id ? `AND l.F_Org_Id = '${F_Org_Id}'` : ''}
      ${F_HouseId ? `AND l.F_HouseId = '${F_HouseId}'` : ''}
      ORDER BY v.F_CreateTime DESC
    `;

    // 构建COUNT查询（仅统计数量）
    const countQuery = `
      SELECT COUNT(*) as total
      FROM nc_livestock as l 
      left JOIN nc_vaccine_log as v ON v.F_liveid = l.F_Id
      left JOIN nc_pasture as p ON p.F_Id = l.F_Org_Id
      left JOIN nc_house as h ON h.F_Id = l.F_HouseId
      WHERE 1=1
      ${searchValue ? `AND (l.F_Title LIKE '%${searchValue}%' OR l.F_IMEI LIKE '%${searchValue}%')` : ''}
      ${F_Org_Id ? `AND l.F_Org_Id = '${F_Org_Id}'` : ''}
      ${F_HouseId ? `AND l.F_HouseId = '${F_HouseId}'` : ''}
    `;

    // 执行COUNT查询获取总数
    const countResult = await queryAsync(countQuery);
    const total = countResult[0].total;
    
    // 计算总页数
    const totalPages = Math.max(1, Math.ceil(total / parsedSize));
    
    // 调整当前页为有效范围（关键修改点）
    const effectivePage = Math.min(parsedPage, totalPages);
    
    // 添加上分页限制（使用调整后的页码）
    const listQuery = `${baseQuery} LIMIT ${(effectivePage - 1) * parsedSize}, ${parsedSize}`;

    // 执行分页查询获取数据列表
    const listResult = await queryAsync(listQuery);

    // 返回包含总数和列表的数据结构（更新当前页信息）
    res.send(zSend({
        total,
        list: listResult
    }));
  } catch (err) {
    console.error(err);
    res.send(zSend('服务器内部错误', 500));
  }
});

// 添加疫苗记录
router.post('/add', async (req, res, next) => {
    const {F_liveid,F_Title,F_Address,F_Name,F_JzTime,F_Batch,F_PHone,F_Number,F_Remark} = req.body;
    if(!F_liveid || !F_Title || !F_JzTime || !F_Number){
        res.send(zSend('参数错误', 400))
    }
    const F_Id = Date.now(); // 生成唯一ID
    const F_CreateTime = new Date().toLocaleString(); // 获取当前时间
    const sql = `
      INSERT INTO nc_vaccine_log (F_Id,F_liveid,F_Title,F_Address,F_Name,F_JzTime,F_Batch,F_PHone,F_Number,F_Remark,F_CreateTime)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `
    db.query(sql, [F_Id,F_liveid,F_Title,F_Address,F_Name,F_JzTime,F_Batch,F_PHone,F_Number,F_Remark,F_CreateTime], (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        } else {
            res.send(zSend('添加成功'))
        }
    })
})

// 删除疫苗记录
router.post('/delete', async (req, res, next) => {
    const {F_Id} = req.body;
    if(!F_Id){
        res.send(zSend('参数错误', 400))
    }
    const sql = `DELETE FROM nc_vaccine_log WHERE F_Id = ?`
    db.query(sql, [F_Id], (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        } else {
            res.send(zSend('删除成功'))
        }
    })
})

// 修改疫苗记录
router.post('/update', async (req, res, next) => {
    const {F_Id,F_liveid,F_Title,F_Address,F_Name,F_JzTime,F_Batch,F_PHone,F_Number,F_Remark} = req.body;
    if(!F_Id || !F_liveid || !F_Title || !F_JzTime || !F_Number){
        res.send(zSend('参数错误', 400))
    }
    const sql = `
      UPDATE nc_vaccine_log SET F_liveid = ?, F_Title = ?, F_Address = ?, F_Name = ?, F_JzTime = ?, F_Batch = ?, F_PHone = ?, F_Number = ?, F_Remark = ? WHERE F_Id = ?
    `
    db.query(sql, [F_liveid,F_Title,F_Address,F_Name,F_JzTime,F_Batch,F_PHone,F_Number,F_Remark,F_Id], (err, data) => {
        if (!data) {
            res.send(zSend('服务器内部错误', 500))
        } else {
            res.send(zSend('修改成功'))
        }
    })
})


module.exports = router;